<template>
  <div>
    <el-card>
      <Search ref="searchRef" :search="search" :config="state.config" @import="handleImport" @delete-disliked="handleDeleteDisliked" @delete-filter="handleDeleteFilter"
       @import-images="openImageImportDialog" @export="handleExport"  @pageChange="onPageChange" @search="onSearch"></Search>
      <PromptBox v-loading="state.loading"  v-bind="state"  @del-row="handleDelete" 
     @edit="handleEdit" @replace-image="handleReplaceImage"></PromptBox>
    </el-card>
    <el-dialog
      v-model="taskStatus.progressVisible"
      :title="`${taskStatus.type === 'import' ? '导入' : '导出'}进度`"
      width="300px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="task-progress">
        <el-progress
          :percentage="taskStatus.progress"
          stroke-width="6"
          :status="taskStatus.progress === 100 ? 'success' : 'active'"
        />
        <p class="progress-text">{{ taskStatus.progress }}%</p>
        <p v-if="taskStatus.progress < 100" class="progress-info">
          正在{{ taskStatus.type === 'import' ? '导入' : '导出' }}数据，请稍候...
        </p>
        <p v-if="taskStatus.progress === 100" class="progress-info">
          {{ taskStatus.type === 'import' ? '导入' : '导出' }}完成
          <span v-if="taskStatus.type === 'export'">，即将下载文件</span>
        </p>
      </div>
    </el-dialog>
    <el-dialog
      v-model="imageImportDialog.visible"
      title="批量导入图片"
      width="500px"
    >
      <el-upload
        ref="imageBatchUploader"
        action="#"
        accept=".jpg,.jpeg,.png,.txt"
        :multiple="true"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleBatchFileChange"
        :file-list="imageImportDialog.fileList"
      >
        <el-button type="primary">选择图片和文本文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持JPG、PNG图片文件和TXT文本文件（图片文件名需与文本文件名对应）
          </div>
        </template>
      </el-upload>
      
      <el-form-item label="目标类型" style="margin-top: 15px;">
        <el-select
          v-model="imageImportDialog.classType" 
          placeholder="例如: collect"
        >
        <el-option v-for="option in options" :label="option.label" :value="option.value">
        </el-option>
      </el-select>
      </el-form-item>
      
      <template #footer>
        <el-button @click="imageImportDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmImageImport">确认导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="PromptPanel">
import { commonApi } from '@renderer/api/common';
import { translateApi } from '@renderer/api/translate';
import { ipcService } from '@renderer/services/ipcService';
import { useConfigStore } from '@renderer/stores/configStore';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const searchRef = ref(null);
const configStore = useConfigStore()
const PromptBox = defineAsyncComponent(() => import('./component/PromptBox.vue'));
const Search = defineAsyncComponent(() => import('./component/Search.vue'));

const state = reactive({
    loading: false,
    data: [],
    config: {
      total: 0,
    },
    param: {
      page: 1,
      page_size: 20,
    },
    getUrl: 'sql/get_prompt_items_paged',
    exportUrl: 'sql/export_prompt_items_stream',
})

const taskStatus = reactive({
  type: 'import' as 'import' | 'export', // 任务类型：导入/导出
  loading: false, // 任务加载状态
  progressVisible: false, // 进度对话框显示状态
  progress: 0, // 进度百分比
  taskId: '', // 当前任务ID
  progressTimer: null as NodeJS.Timeout | null // 进度查询定时器
});

const search = computed(() => [
  {
    label: t('message.random.keyName'),
    prop: 'name',
    placeholder: t('message.random.keyName'),
    type: 'input'
  },
  {
    label: t('message.random.customizeName'),
    prop: 'customize_name',
    placeholder: t('message.random.customizeName'),
    type: 'input'
  },
  {
    label: t('message.random.classType'),
    prop: 'class_type',
    placeholder: t('message.random.classType'),
    required: false,
    type: 'select',
    options: [
      { label: 'All', value: '' },
      { label: 'style', value: 'style' },
      { label: 'action', value: 'action' },
      { label: 'collect', value: 'collect' },
      { label: 'cloth', value: 'cloth' },
      { label: 'preset', value: 'preset' }
    ]
  },
  {
    label: t('message.random.favorite'),
    prop: 'favorite',
    placeholder: t('message.random.favorite'),
    required: false,
    type: 'select',
    options: [
      { label: 'All', value: '' },
      { label: 'true', value: 1 },
      { label: 'false', value: 0 }
    ]
  },
  {
    label: t('message.random.disliked'),
    prop: 'disliked',
    placeholder: t('message.random.disliked'),
    required: false,
    type: 'select',
    options: [
      { label: 'All', value: '' },
      { label: 'true', value: 1 },
      { label: 'false', value: 0 }
    ]
  },
  {
    label: t('message.random.id'),
    prop: 'id',
    placeholder: t('message.random.id'),
    type: 'input'
  },
]);

const onSearch = (data) => {
  state.param = {
    ...state.param,
    ...data,
  }
  searchRef.value.pageReset()
}

const getPromptData = ()=>{
  state.loading = true
  commonApi().getPromptDataByPage(state.param).then((res) => {
      state.data = res.data.data;
      state.config.total= res.data.pagination.total
      state.param.page = res.data.pagination.page
  }).finally(()=>{
    state.loading = false
  })
}

const onPageChange = (page) => {
  state.param.page = page.pageNum
  state.param.page_size = page.pageSize
  getPromptData()
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该标签？', '警告', { type: 'warning' })
    commonApi().deletePromptItem({id:id}).then((res) => {
      ElMessage.success('删除成功')
      getPromptData()
    })
  } catch (error) {
    // 用户取消不处理
  }
}

const handleDeleteDisliked = async ()=>{
  try {
    await ElMessageBox.confirm('确定删标记的标签？', '警告', { type: 'warning' })
    commonApi().deleteDislikedPromptItem().then((res) => {
      if(res.data.result){
        ElMessage.success("删除成功")
        getPromptData()
      }
      else{
        ElMessage.error(JSON.stringify(res.data))
      }
    })
  } catch (error) {
    // 用户取消不处理
  }
}

const handleDeleteFilter = async (data)=>{
  try {
    await ElMessageBox.confirm('确定删筛选的记录？', '警告', { type: 'warning' })
    commonApi().deletePromptItemsByFilter(data).then((res) => {
      if(res.data.success){
        ElMessage.success(JSON.stringify(res.data))
        getPromptData()
      }
      else{
        ElMessage.error(JSON.stringify(res.data))
      }
    })
  } catch (error) {
  }
}

const handleEdit =(data)=>{
  commonApi().updatePromptItem(data).then((res) => {
    getPromptData()
  })
}

const handleReplaceImage = async (id:string,file:File)=>{
  try {
    const imageSave = `${configStore.config.imagesPath}\\collections\\${id}.webp`
    const result = await ipcService.saveWebpImage(
      file,
      imageSave,
    )
    if (result.success) {
      configStore.updateImageVersion(imageSave);
      ElMessage.success('图片保存成功');
      getPromptData()
    } else {
      ElMessage.warning('图片保存失败，但记录已创建');
    }
  } catch (error) {
    ElMessage.error(`图片保存失败: ${error.message}`);
  }
}

const handleExport = async (data:any) => {
  try {
    taskStatus.type = 'export';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `export_${Date.now()}`;
    // 调用导出接口
    const params = {
      ...data,
      taskId: taskStatus.taskId
    };

    const response = await commonApi().exportPromptItemStream(params);
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `prompt_${new Date().getTime()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 清除定时器并最后一次查询进度
    clearProgressTimer();
    await fetchTaskProgress();
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
    clearProgressTimer();
    taskStatus.progressVisible = false;
  } finally {
    // 确保最终状态重置
    if (taskStatus.progress === 100 || taskStatus.progress === -1) {
      taskStatus.loading = false;
    }
    clearProgressTimer();
  }
};

const handleImport = async (file: File) => {
  try {
    taskStatus.type = 'import';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `import_${Date.now()}`;
    
    // 启动进度查询定时器（保持运行直到任务结束）
    taskStatus.progressTimer = setInterval(() => {
      if (taskStatus.progressVisible && taskStatus.taskId) {
        fetchTaskProgress();
      }
    }, 200);

    // 使用FormData上传文件内容
    const formData = new FormData();
    formData.append('file', file); // 添加文件对象
    formData.append('taskId', taskStatus.taskId); // 添加任务ID

    // 调用API时传递FormData
    const res = await commonApi().importPromptItemCsv(formData);
    
    if (res.data.success) {
      ElMessage.success('提示词组导入任务已启动');
    } else {
      // 仅当接口明确返回失败时才清理
      taskStatus.progressVisible = false;
      ElMessage.error(JSON.stringify(res.data)|| '导入失败');
      clearProgressTimer();
    }

    return false; // 阻止默认上传
  } catch (error) {
    ElMessage.error('导入失败');
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
    return false;
  }
};

// 统一进度查询函数（支持导入/导出）
const fetchTaskProgress = async () => {
  try {
    if (!taskStatus.taskId) return;

    const response = await translateApi().getTaskProgress(taskStatus.taskId);
    taskStatus.progress = response.data.progress;

    // 进度完成或取消时，清理定时器并隐藏进度条
    if (response.data.progress === 100 || response.data.progress === -1) {
      clearProgressTimer(); // 任务结束才停止查询
      if(taskStatus.type === 'import'){
        getPromptData()
      }
      setTimeout(() => {
        taskStatus.progressVisible = false;
        taskStatus.loading = false;
      }, 1000);
    }
  } catch (error) {
    console.error(`获取${taskStatus.type === 'import' ? '导入' : '导出'}进度失败:`, error);
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
  }
};

// 清除进度定时器（统一封装）
const clearProgressTimer = () => {
  if (taskStatus.progressTimer) {
    clearInterval(taskStatus.progressTimer);
    taskStatus.progressTimer = null;
  }
};

// 新增：图片批量导入相关状态
const imageImportDialog = reactive({
  visible: false,
  fileList: [],
  classType: 'collect',
  selectedFiles: [] // 存储选中的文件
});

// 新增：图片批量上传组件引用
const imageBatchUploader = ref();
const options = [
      { label: 'style', value: 'style' },
      { label: 'action', value: 'action' },
      { label: 'collect', value: 'collect' },
      { label: 'cloth', value: 'cloth' },
      { label: 'preset', value: 'preset' }
]

const handleBatchFileChange = (uploadFile, uploadFiles) => {
  imageImportDialog.fileList = uploadFiles;
  imageImportDialog.selectedFiles = uploadFiles.map(f => f.raw);
};

// 新增：打开图片批量导入对话框
const openImageImportDialog = () => {
  // 可以预设目标路径
  imageImportDialog.classType = 'collect';
  imageImportDialog.visible = true;
  imageImportDialog.fileList = [];
  imageImportDialog.selectedFiles = [];
};

// 新增：确认图片批量导入
const confirmImageImport = async () => {
  if (imageImportDialog.selectedFiles.length === 0) {
    ElMessage.warning('请选择至少一个文件');
    return;
  }
  
  if (!imageImportDialog.classType) {
    ElMessage.warning('请输入目标保存类型');
    return;
  }
  
  try {
    // 初始化任务状态
    taskStatus.type = 'import';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `image_import_${Date.now()}`;
    

    // 构建FormData
    const formData = new FormData();
    
    // 添加所有选中的文件
    imageImportDialog.selectedFiles.forEach(file => {
      formData.append('files', file);
    });

    // 添加任务ID和目标路径
    formData.append('taskId', taskStatus.taskId);
    formData.append('targetPath', `${configStore.config.imagesPath}\\collections`);
    formData.append('classType', imageImportDialog.classType);

    taskStatus.progressTimer = setInterval(() => {
      if (taskStatus.progressVisible && taskStatus.taskId) {
        fetchTaskProgress();
      }
    }, 500);

    // 调用图片批量导入API
    const res = await commonApi().importPromptItemImages(formData);
    
    if (res.data.success) {
      ElMessage.success('图片导入任务已启动');
      imageImportDialog.visible = false;
    } else {
      ElMessage.error(res.data.message || '导入失败');
      clearProgressTimer();
      taskStatus.progressVisible = false;
    }
  } catch (error) {
    console.error('图片批量导入失败:', error);
    ElMessage.error('导入失败，请重试');
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
  }
};

onMounted(()=>{
  getPromptData()
})
</script>
